/*
 * Copyright 2011 Philippe Blanc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package me.l1k3.core.client.impl;

import com.google.gwt.dom.client.Element;

import me.l1k3.core.client.Core;
import me.l1k3.core.client.inter.ComputedStyleProperty;

public final class ComputedStylePropertyImplDOM implements ComputedStyleProperty {

    @Override
    public final String getComputedStyleProperty(Element element, String property) {
        property = Core.camelCaseToDash(property);
        
        if(property.equals("float")) {
            property = "css-float";
        }

        return getComputedStylePropertyImpl(element, property);
    }

    @Override
    public final double getComputedStylePropertyAsPixel(Element element, String property) {
        property = Core.camelCaseToDash(property);
        
        if(property.equals("line-height")) {
            return getLineHeightAsPixel(element);
        }
        
        return Core.parseDouble(getComputedStylePropertyImpl(element, property));
    }

    private final native String getComputedStylePropertyImpl(Element e, String p) /*-{
        return e.ownerDocument.defaultView.getComputedStyle(e,null).getPropertyValue(p);
    }-*/;
    
    private final native double getLineHeightAsPixel(Element e) /*-{
        var h = e.ownerDocument.defaultView.getComputedStyle(e,null).getPropertyValue("line-height");
        if (/^\D+/.test(h)) {
            var copy = e.cloneNode(false);
            copy.style.padding="0px";
            copy.style.border="none";
            copy.innerHTML="x";
            var parent = e.parentNode? e.parentNode : e;
            parent.appendChild(copy);
            h = copy.offsetHeight;
            parent.removeChild(copy);
            delete copy;
        }
    
        return parseFloat(h);
    }-*/;
}
